package org.example.controller;

import org.example.entity.User;
import org.example.exception.AccountExitException;
import org.example.exception.PermissionsDenyException;
import org.example.service.ClanService;
import org.example.service.FamilyService;
import org.example.service.RedisService;
import org.example.service.UserService;
import org.example.vo.ChildVo;
import org.example.vo.RegisterVo;
import org.example.utils.R;
import org.example.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import static org.example.interceptor.LoginInterceptor.threadLocal;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    FamilyService familyService;
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;
    @Autowired
    ClanService clanService;
    @PostMapping("/combiteChild")
    public @ResponseBody R createFamily(@RequestBody RegisterVo registerVo) throws AccountExitException, PermissionsDenyException {
        User parent = threadLocal.get();
        User child = familyService.createFamily(registerVo,parent);
        ChildVo childVo = new ChildVo(child.name, child.id);
        return  R.ok().setData(childVo);
    }
    @Transactional
    @PostMapping("/updateUser")
    public @ResponseBody R updateChild(@RequestBody User target) throws PermissionsDenyException, Exception {
        UserVO uservo = userService.updateUser(target);
        return R.ok().setData(uservo);
    }
//    @PostMapping("/updateSelf")
//    public @ResponseBody R updateSelf(@RequestBody User self, HttpServletRequest httpServletRequest) throws PermissionsDenyException {
//        User cur = threadLocal.get();
//        //首先是自我鉴别，只能更新别人
//        if(self.id!=cur.id) throw new PermissionsDenyException();
//        userService.saveOrUpdate(self);
//        redisService.setUser(httpServletRequest.getHeader("token"),self);
//        return R.ok().setData(self);
//    }

}
